<script setup lang="ts">
import { computed, onMounted, watch, ref } from 'vue';
import { $t } from '@/locales';
import { queryMenuPermission, queryPermissionIdsWithRoleId, add } from '@/service/api/system-manage';

defineOptions({ name: 'DhkPermissionDialog' });

interface Props {
  /** the roleId */
  roleId: number;
}

const props = defineProps<Props>();

const visible = defineModel<boolean>('visible', {
  default: false
});

// Emit events
interface Emits {
  (e: 'close'): void;
  (e: 'success'): void;
}

const emit = defineEmits<Emits>();

function closeModal() {
  visible.value = false;
  emit('close');
}

const title = computed(() => $t('common.edit') + ' 权限配置');

// 树形权限数据
const permissionTree = ref<any[]>([]);
// 选中的权限ID列表
const checkedPermissionIds = ref<number[]>([]);
// 加载状态
const loading = ref<boolean>(false);
const submitLoading = ref<boolean>(false);
const fetchError = ref<boolean>(false);

// 权限树配置
const defaultProps = {
  children: 'children',
  label: 'title'
};

/**
 * 获取所有权限菜单树
 */
async function getPermissionTree() {
  loading.value = true;
  fetchError.value = false;
  try {
    const res = await queryMenuPermission();
    if (res && res.data) {
      // Convert to array if needed
      permissionTree.value = Array.isArray(res.data) ? res.data : [res.data];
      console.log('Permission tree loaded:', permissionTree.value);
    } else {
      console.error('Failed to load permission tree:', res);
      fetchError.value = true;
    }
  } catch (error) {
    console.error('获取权限菜单树失败:', error);
    window.$message?.error('获取权限菜单树失败');
    fetchError.value = true;
  } finally {
    loading.value = false;
  }
}

/**
 * 获取角色已分配的权限ID列表
 */
async function getRolePermissionIds() {
  if (!props.roleId) {
    console.warn('No roleId provided, skipping permission fetch');
    return;
  }
  
  loading.value = true;
  fetchError.value = false;
  try {
    const res = await queryPermissionIdsWithRoleId(props.roleId);
    if (res && res.data) {
      // Ensure we have a proper array of numbers
      checkedPermissionIds.value = Array.isArray(res.data) 
        ? res.data.map(id => typeof id === 'number' ? id : Number(id))
        : [];
      console.log('Checked permissions loaded:', checkedPermissionIds.value);
    } else {
      console.error('Failed to load role permissions:', res);
      fetchError.value = true;
    }
  } catch (error) {
    console.error('获取角色权限IDs失败:', error);
    window.$message?.error('获取角色权限列表失败');
    fetchError.value = true;
  } finally {
    loading.value = false;
  }
}

/**
 * 处理节点选择变化
 */
function handleCheck(data: any, checked: any) {
  // Ensure we have a valid array of numbers
  if (checked && checked.checkedKeys) {
    checkedPermissionIds.value = Array.isArray(checked.checkedKeys) 
      ? checked.checkedKeys.map(id => typeof id === 'number' ? id : Number(id))
      : [];
    console.log('Updated checked permissions:', checkedPermissionIds.value);
  }
}

/**
 * 提交权限更新
 */
async function handleSubmit() {
  if (!props.roleId) {
    window.$message?.warning('请选择角色');
    return;
  }

  submitLoading.value = true;
  try {
    // 构造提交参数，符合SysRolePermissionUpdateDTO格式
    const params = {
      roleId: props.roleId,
      permissionIds: checkedPermissionIds.value
    };

    console.log('Submitting permissions:', params);
    const result = await add(params);
    
    if (result) {
      window.$message?.success('权限更新成功');
      emit('success');
      closeModal();
    } else {
      window.$message?.error('提交失败');
    }
  } catch (error) {
    console.error('提交权限配置失败:', error);
    window.$message?.error('提交失败');
  } finally {
    submitLoading.value = false;
  }
}

/**
 * 初始化数据
 */
function init() {
  console.log('Initializing with roleId:', props.roleId);
  // Reset states
  checkedPermissionIds.value = [];
  permissionTree.value = [];
  fetchError.value = false;
  
  // Fetch data
  getPermissionTree();
  getRolePermissionIds();
}

// 监听对话框显示状态
watch(visible, (newVal) => {
  if (newVal) {
    console.log('Dialog opened, initializing data...');
    init();
  }
});

// 监听角色ID变化
watch(() => props.roleId, (newVal, oldVal) => {
  if (visible.value && newVal !== oldVal) {
    console.log('RoleId changed, reinitializing...');
    init();
  }
});

// 组件挂载时如果对话框可见则初始化
onMounted(() => {
  if (visible.value) {
    console.log('Component mounted with visible=true');
    init();
  }
});
</script>

<template>
  <ElDialog 
    v-model="visible" 
    :title="title" 
    width="600px" 
    destroy-on-close
    @close="closeModal"
  >
    <div v-loading="loading" class="h-400px overflow-auto">
      <div v-if="fetchError" class="flex-center h-full">
        <ElResult
          icon="error"
          title="操作失败"
          sub-title="获取权限数据失败，请刷新重试"
        >
          <template #extra>
            <ElButton type="primary" @click="init">重新加载</ElButton>
          </template>
        </ElResult>
      </div>
      <ElTree
        v-else
        ref="permissionTree"
        node-key="id"
        :data="permissionTree"
        :props="defaultProps"
        :default-checked-keys="checkedPermissionIds"
        :default-expanded-keys="checkedPermissionIds"
        show-checkbox
        @check="handleCheck"
      />
    </div>
    <template #footer>
      <ElSpace class="w-full justify-end">
        <ElButton @click="closeModal">{{ $t('common.cancel') }}</ElButton>
        <ElButton 
          type="primary" 
          :loading="submitLoading" 
          @click="handleSubmit"
        >
          {{ $t('common.confirm') }}
        </ElButton>
      </ElSpace>
    </template>
  </ElDialog>
</template>

<style scoped>
.h-400px {
  height: 400px;
}
.h-full {
  height: 100%;
}
.flex-center {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
